package com.estun.backroundManagementService.modules.product.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.estun.backroundManagementService.domain.BaseResponse;
import com.estun.backroundManagementService.modules.alarm.model.AlarmResult;
import com.estun.backroundManagementService.modules.alarm.service.StationAlarmService;
import com.estun.backroundManagementService.modules.product.mapper.ProductValueThresholdMapper;
import com.estun.backroundManagementService.modules.product.model.Product;
import com.estun.backroundManagementService.modules.product.model.ProductStationTime;
import com.estun.backroundManagementService.modules.product.model.ProductValue;
import com.estun.backroundManagementService.modules.product.model.ProductValueThreshold;
import com.estun.backroundManagementService.modules.product.model.res.ProductValueToDetailPage;
import com.estun.backroundManagementService.modules.product.service.ProductService;
import com.estun.backroundManagementService.modules.product.service.ProductStationTimeService;
import com.estun.backroundManagementService.modules.product.service.ProductValueService;
import com.estun.backroundManagementService.modules.testResult.mapper.TestResultMapper;
import com.estun.backroundManagementService.modules.testResult.model.TestResult;
import com.estun.backroundManagementService.modules.testResult.service.TestResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品参数表 前端控制器
 * </p>
 *
 * @author machine
 * @since 2023-02-14
 */
@Slf4j
@RestController
@Api(tags = "ProductValueController", description = "产品参数管理")
@RequestMapping("/product/productValue")
@AllArgsConstructor
public class ProductValueController {

    private final ProductValueService productValueService;
    private final ProductStationTimeService productStationTimeService;
    private final StationAlarmService stationAlarmService;
    private final ProductService productService;

    @Autowired
    private TestResultService testResultService;
    @Autowired
    private ProductValueThresholdMapper productValueThresholdMapper;

    @ApiOperation(value = "产品参数追溯信息查询")
    @RequestMapping(value = "/getByProductId/{productId}", method = RequestMethod.GET)
    @ResponseBody
    public BaseResponse queryPage(@PathVariable String productId) {
        List<ProductValue> productValueList = productValueService.list(new QueryWrapper<ProductValue>().eq("product_id", productId));
        Product product = productService.getById(productId);
        String productNo = product.getProductNo();
        String stationId = product.getStationId();
        List<ProductStationTime> productStationTimeList = productStationTimeService.list(new QueryWrapper<ProductStationTime>().eq("product_id", productId));
        if (StringUtils.isNotBlank(product.getLowerCode()) && product.getType() == 1) {
            List<Product> list = productService.list(new QueryWrapper<Product>().eq("type", 2).eq("lower_code", product.getLowerCode()));
            if (CollectionUtils.isEmpty(list)) {
                log.error("下游路板产品数据丢失,productId：{}", productId);
            } else {
                if (list.size() > 1) {
                    log.error("下游路板产品数据重复,productId：{}", productId);
                }
                Long lowerProductId = list.get(0).getId();
                productStationTimeList.addAll(productStationTimeService.list(new QueryWrapper<ProductStationTime>().eq("product_id", lowerProductId)));
                List<ProductValue> lowerProductValueList = productValueService.list(new QueryWrapper<ProductValue>().eq("product_id", lowerProductId));
                productValueList.addAll(lowerProductValueList);
            }
        }

        Map<String, List<ProductValue>> valueMap = productValueList.stream()
                .collect(Collectors.groupingBy(ProductValue::getStationId));
        //按照时间进行排序
        productStationTimeList.sort(Comparator.comparing(ProductStationTime::getStartTime));

        LinkedHashMap<String, JSONObject> mergedMap = new LinkedHashMap<>();
        for (ProductStationTime productStationTime : productStationTimeList) {
            List<ProductValue> productValues = valueMap.get(productStationTime.getStationId());
            // 复制一个新的实体类出来
            List<ProductValueToDetailPage> productValueToDetailPageList = new ArrayList<>();
            if(productValues!= null){
                for (ProductValue productValue : productValues) {
                    ProductValueToDetailPage productValueToDetailPage = new ProductValueToDetailPage();
                    BeanUtils.copyProperties(productValue, productValueToDetailPage);
                    productValueToDetailPageList.add(productValueToDetailPage);
                }
            }
            for (ProductValueToDetailPage value : productValueToDetailPageList) {
                String realValue ="";
                // 处理data中的数据，取出最大值比较
                if(value.getValue() == null){
                    String[] parts = value.getData().split(",");
                    double max = Double.MIN_VALUE;
                    for (String part : parts) {
                        double parseDouble = Double.parseDouble(part.trim());
                        if (parseDouble > max) {
                            max = parseDouble;
                        }
                    }
                    DecimalFormat df = new DecimalFormat("#.##");
                    realValue = df.format(max);
                }else {
                    realValue =String.valueOf(value.getValue());
                }
                // 处理阈值
                String minThreshold ="";
                String maxThreshold ="";
                String isQualified ="0";
                String name = value.getName();
                QueryWrapper<ProductValueThreshold> queryWrapper =new QueryWrapper<>();
                queryWrapper.eq("name",name);
                queryWrapper.eq("station_id",value.getStationId());
                List<ProductValueThreshold> productValueThresholdList = productValueThresholdMapper.selectList(queryWrapper);
                if(!productValueThresholdList.isEmpty()){
                    for (ProductValueThreshold productValueThreshold : productValueThresholdList) {
                        String thresholdType = productValueThreshold.getThresholdType();
                        String threshold = productValueThreshold.getValue();
                        if("max".equals(thresholdType)){
                            maxThreshold = threshold;
                        }else if("min".equals(thresholdType)){
                            minThreshold = threshold;
                        }
                    }
                    // 判断真实值是否在阈值内
                    if(StringUtils.isNotEmpty(maxThreshold) && StringUtils.isNotEmpty(minThreshold)){
                        double realValueNum = Double.parseDouble(realValue);
                        double minThresholdNum = Double.parseDouble(minThreshold);
                        double maxThresholdNum = Double.parseDouble(maxThreshold);
                        if (realValueNum < minThresholdNum || realValueNum > maxThresholdNum) {
                            isQualified ="1";
                        }
                    }else if(StringUtils.isNotEmpty(maxThreshold) && StringUtils.isEmpty(minThreshold)){
                        double realValueNum = Double.parseDouble(realValue);
                        double maxThresholdNum = Double.parseDouble(maxThreshold);
                        if (realValueNum > maxThresholdNum) {
                            isQualified ="1";
                        }
                    }else if(StringUtils.isEmpty(maxThreshold) && StringUtils.isNotEmpty(minThreshold)){
                        double realValueNum = Double.parseDouble(realValue);
                        double minThresholdNum = Double.parseDouble(minThreshold);
                        if (realValueNum < minThresholdNum) {
                            isQualified ="1";
                        }
                    }
                }
                value.setIsQualified(isQualified);
                value.setMaxThreshold(maxThreshold);
                value.setMinThreshold(minThreshold);
            }
            // 增加测试站测试参数
            if(productStationTime.getStationId().contains("TE")){
                QueryWrapper<TestResult> testResultQueryWrapper = new QueryWrapper<>();
                testResultQueryWrapper.eq("product_no", productNo);
                List<TestResult> testResultList = testResultService.list(testResultQueryWrapper);
                for (TestResult testResult : testResultList) {
                    ProductValueToDetailPage productValue =new ProductValueToDetailPage();
                    productValue.setId(Long.valueOf(testResult.getId()));
                    productValue.setName(testResult.getConditionName() + "_" +testResult.getTestItem() + "("+testResult.getUnits()+")" +"_" +testResult.getItemResult());
                    productValue.setValue(Float.valueOf(testResult.getValue()));
                    productValue.setStationId(stationId);
                    productValue.setMaxThreshold(testResult.getMax());
                    productValue.setMinThreshold(testResult.getMin());
                    if("OK".equals(testResult.getItemResult())){
                        productValue.setIsQualified("0");
                    }else {
                        productValue.setIsQualified("1");
                    }
                    productValueToDetailPageList.add(productValue);
                }
            }
            if (productValueToDetailPageList != null) {
                productValueToDetailPageList.forEach(row -> {
                    String data = row.getData();
                    if (StringUtils.isNotBlank(data)) {
                        String newData = cleanString(data);
                        row.setData(newData.isEmpty() ? null : newData);
                    }
                });
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("productValues", productValueToDetailPageList);
            jsonObject.put("productStationTime", productStationTime);
            mergedMap.put(productStationTime.getStationId(), jsonObject);
        }
//
//        // 合并两个 Map，将相同键的值合并为 JSONObject，并按照键的大小排序
//        Map<String, JSONObject> mergedMap = valueMap.entrySet().stream()
//                .sorted(Map.Entry.comparingByKey()) // 按键排序
//                .collect(Collectors.toMap(Map.Entry::getKey, entry -> {
//                    String key = entry.getKey();
//                    List<ProductValue> values = entry.getValue();
//                    ProductStationTime stationTime = stationTimeMap.get(key);
//                    JSONObject jsonObject = new JSONObject();
//                    jsonObject.put("productValues", values);
//                    jsonObject.put("productStationTime", stationTime);
//                    return jsonObject;
//                }, (e1, e2) -> e1, LinkedHashMap::new)); // 保留排序
        return BaseResponse.success(mergedMap);
    }

    private static String cleanString(String input) {
        input = input.replaceAll("undefined", "");
        // 去除开头和结尾的逗号
        String trimmedString = input.replaceAll("^,+", "").replaceAll(",$", "");

        // 保证相邻两个数字之间只有一个逗号
        String[] parts = trimmedString.split(",");
        StringBuilder result = new StringBuilder();

        for (String part : parts) {
            // 去除多余的逗号
            if (!part.isEmpty()) {
                if (result.length() > 0) {
                    result.append(",");
                }
                result.append(part);
            }
        }

        return result.toString();
    }

    @ApiOperation(value = "产品参数按站查询")
    @RequestMapping(value = "/getDataByLatestStationId", method = RequestMethod.GET)
    @ResponseBody
    public BaseResponse getDataByLatestStationId(@RequestParam String stationId) {
        List<ProductValue> productValueList = productValueService.getByLatestStationId(stationId);
        Product product = productValueService.getProductByStationId(stationId);

        Map<String, Object> map = new HashMap<>();
        map.put("product", product);
        map.put("productValueList", productValueList);
        if (product != null) {
            List<ProductStationTime> list = productStationTimeService.list(new QueryWrapper<ProductStationTime>().eq("product_id", product.getId()).eq("station_id", stationId));
            if(CollectionUtils.isNotEmpty(list)){
                ProductStationTime stationTime = list.get(0);
                map.put("stationTime", stationTime);
            }

        }

        List<AlarmResult> alarmList = stationAlarmService.getByLatestAlarmList(stationId);
        map.put("alarmList", alarmList);

        return BaseResponse.success(map);
    }
}

